//防止播放器滑动穿透
$('#vBox').get(0).addEventListener('touchmove', function(e) {
	e.preventDefault();
}, {
	passive: false
});

mui.init({
	beforeback: function() {
		//获得列表界面的webview
		var parentOobj = plus.webview.currentWebview().opener();

		//触发列表界面的自定义事件（dataList）,从而进行数据刷新
		mui.fire(parentOobj, 'dataList');
		//返回true，继续页面关闭逻辑
		return true;
	},
// 	,
// 	pullRefresh: {
// 		container: "#refreshContainer", //下拉刷新容器标识，querySelector能定位的css选择器均可，比如：id、.class等
// 		down: {
// 			style: 'circle', //必选，下拉刷新样式，目前支持原生5+ ‘circle’ 样式
// 			color: '#2BD009', //可选，默认“#2BD009” 下拉刷新控件颜色
// 			height: '50px', //可选,默认50px.下拉刷新控件的高度,
// 			range: '100px', //可选 默认100px,控件可下拉拖拽的范围
// 			offset: '0px', //可选 默认0px,下拉刷新控件的起始位置
// 			auto: false, //可选,默认false.首次加载自动上拉刷新一次
// 			callback: pullDown_refresh //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
// 		}
// 	}
});
mui('.mui-scroll-wrapper').scroll({
	bounce: true,
	indicators: true,
	deceleration: 0.0005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
});

/* document.addEventListener("swipeleft", function(){
	if(class_details.tabIndex < 3) {
		class_details.tabIndex ++;	
	}else{
		class_details.tabIndex = 3;
	}
	// mui('.mui-scroll-wrapper').scroll().scrollTo(0,0,100);
}); */

/* document.addEventListener("swiperight", function(){
	if(class_details.tabIndex > 1) {
		class_details.tabIndex --;
	}else{
		class_details.tabIndex = 1;
	}
	// mui('.mui-scroll-wrapper').scroll().scrollTo(0,0,100);
}); */

var class_id;
var flag = true;
var class_details;
var connectionStatus;
var video = null;
var player = null;

mui.plusReady(function() {
	hideScrollBar();
	//返回全屏
	var old_back = mui.back;
	mui.back = function() {
	    plus.navigator.setFullscreen(false);
	   /* var A = plus.webview.getLaunchWebview();
		A.evalJS('window.location.reload()');*/
	    old_back();
	}
	var self = plus.webview.currentWebview();
	class_id = self.cid;
	class_details = new Vue({
		el: '#class_details',
		data: {
			details: '',
			mulu_list: '',
			pig_tea: '',
			tabIndex: '1',
			url: '',
			PlayURL: '',
			CoverURL: '',
			filename: '',
			status: '',
			collection_status: '',
			loginSta: '',
			auditStatus:'no',
		},
		mounted() {
			var self = this;
			this.getclass_details();
			this.updateStatus();
			this.$nextTick(function () {
				self.auditStatus = plus.storage.getItem('auditStatus') ? plus.storage.getItem('auditStatus') : 'no';
			})
		},
		methods: {
			updateStatus: function() {
				showWatting();
				var api_host = plus.storage.getItem('HOST_URL');
				var self = this;
				mui.ajax({
					url: api_host + '/api/linxuan/user/checkLoginStatus',
					dataType: 'json',
					headers: {
						'User-Token': plus.storage.getItem('UserToken')
					},
					timeout: 3000,
					type: 'get',
					success: function(msg) {
						if (msg.code == 1) {
							self.loginSta = 1;
							self.user_detail = msg.data;
						} else {
							self.loginSta = 0;
						}
					},
					error: function(xhr, type, errorThrown) {
						mui.toast('登录状态请求失败请重试', {
							duration: '300'
						});
					},
					complete: function() {
						plus.nativeUI.closeWaiting();
					}
				});
			},

			getclass_details: function() {
				 showWatting();

				var api_host = plus.storage.getItem('HOST_URL');

				mui.ajax({
					url: api_host + '/api/course/course/getonebyId',
					dataType: 'json',
					data: {
						'id': class_id
					},
					type: 'get',
					headers: {
						'User-Token': plus.storage.getItem('UserToken')
					},
					timeout: 3000,
					success: function(msg) {
						if (msg.code == 1) {
							class_details.details = msg.data.course;
							//添加判断，如果有听课权限，则默认切换到目录tab
							if(msg.data.course.isFree== '1' || (msg.data.course.isFree== '0' && msg.data.course.is_buy== 'YES_PAY' )){
								class_details.tabIndex = 2;
							}
							class_details.collection_status = msg.data.course.star;
							class_details.mulu_list = msg.data.items;
							class_details.pig_tea = msg.data.teacher;
							class_details.isFree = msg.data.course.isFree;
							class_details.is_buy = msg.data.is_buy;
							mui(".course_ad").on('tap', 'img', function() {
								var src = $(this).attr('src');
								openBigPic([src]);
							});
						}
					},
					error: function() {
						mui.toast('加载失败!');
					},
					complete: function() {
						plus.nativeUI.closeWaiting();
					}
				})
			},
			select_tab: function(e) {
				this.tabIndex = e.target.getAttribute('tab-index');
			},
			qq: function() {
				customerService();
			},
			favorite: function(courseid, name) {
				updateProductCollection('course', courseid, name.title, name, class_details);
			},
			begin_learn: function() {
				if (class_details.loginSta == 0) {
					mui.toast('您还没有登录，请先登录账号再进行操作哦！');
					setTimeout(function() {
						mui.openWindow({
							url: '../../logReg/login.html',
							createNew: false,
							id: 'loginHtml',
							show: {
								autoShow: true,
								anishow: 'pop-in',
								duration: 400
							},
							waiting: {
								autoShow: false,
							}
						});
					}, 1000)
				} else {
					document.querySelector('#item2').style.display = "block";
					document.querySelector('#item1').style.display = "none";
					class_details.tabIndex = 2;
					//开始学习的会员自动加入课程
					var api_host = plus.storage.getItem('HOST_URL');
					var self = this;
					mui.ajax({
						url: api_host + '/api/course/course/putMyCourse',
						dataType:'json',
						data:{'id': class_id},
						type:'get',
						headers: {
							'User-Token': plus.storage.getItem('UserToken')
						},
						timeout: 3000,
						success:function(msg){
							if(msg.code == 1){
								mui.toast('已加入课程,点击课程目录开始学习',{
									duration: '300'
								});
							}else{
								mui.toast('点击课程目录开始学习',{
									duration: '300'
								});
							}
						},
						error:function(xhr, type, errorThrown){
							mui.toast('点击课程目录开始学习',{
								duration: '300'
							});
						},
						complete:function(){
							plus.nativeUI.closeWaiting();
						}
					});
					
					document.querySelector('#item2').style.display = "block";
					document.querySelector('#item1').style.display = "none";
					class_details.tabIndex = 2;
					// mui.toast("点击对应的课时开始学习");
				}
			},
			
			limit_course:function(){
				mui.toast("该课程为限制课程，请联系客服");
				return;
			},
			
			buy: function(courseId, title, largePicture, price) {
				if (class_details.loginSta == 1) {
					mui.openWindow({
						url: 'courseOrder.html',
						extras: {
							'courseId': courseId,
							'title': title,
							'largePicture': largePicture,
							'price': price
						},
						createNew: false,
						show: {
							autoShow: true,
							anishow: 'pop-in',
							duration: 400
						},
						waiting: {
							autoShow: false,
						}
					});
				} else {
					mui.toast('您还没有登录，正在前往登录页面...', {
						duration: '800',
						type: 'div'
					});
					setTimeout(function() {
						mui.openWindow({
							url: '../../logReg/login.html',
							createNew: false,
							id: 'loginHtml',
							show: {
								autoShow: true,
								anishow: 'pop-in',
								duration: 400
							},
							waiting: {
								autoShow: false,
							}
						});
					}, 1000)
				}
			},

			video: function(courseId, taskId, type, status,picture,startTime,endTime) {
				plus.navigator.setFullscreen(true);
			var vHeight = $(window).width()*9/16;
			if (class_details.loginSta == 1) {
				var api_host = plus.storage.getItem('HOST_URL');
				var option = {
					id: "J_prismPlayer",
					width: '100%',
					height: vHeight,
					preload: true,
					controlBarVisibility: "click",
					useH5Prism: true,
					autoplay: true,
					"replay": true,
					playsinline: true,
					prismType: 2,
					vid: '',
					accId: '',
					accSecret: '',
					apiKey: '',
					showBarTime: 5000,
					cover: '',
					source: '',
					playsinline: true,
					skinLayout: [{
							name: "bigPlayButton",
							align: "blabs",
							x: 30,
							y: 80
						},
						{
							name: "H5Loading",
							align: "cc"
						},
						{
							name: "controlBar",
							align: "blabs",
							x: 0,
							y: 0,
							children: [{
									name: "progress",
									align: "tlabs",
									x: 0,
									y: 0
								}, //隐藏进度条
								{
									name: "playButton",
									align: "tl",
									x: 15,
									y: 13
								},
								{
									name: "timeDisplay",
									align: "tl",
									x: 10,
									y: 6
								},
								{
									name: "fullScreenButton",
									align: "tr",
									x: 20,
									y: 12.5
								},
								{
									name: "volume",
									align: "tr",
									x: 20,
									y: 12.5
								},
								{
									name: "speedButton",
									align: "tr",
									x: 10,
									y: 23
								},
							]
						}
					]
				};

				if (class_details.details.is_buy == 'YES_PAY' || class_details.details.isFree == 1) {
					connectionStatus = plus.networkinfo.getCurrentType();

					if (typeof status == 'string' && status.constructor == String) {
						var begin_time = startTime*1000;
						var end_time   = endTime*1000; 
						var nowTime = new Date().getTime();
						
						if (status == '敬请期待') {
							mui.toast("课时尚未发布");
							return;
						}else{
							if (begin_time >nowTime) {
								mui.toast("课时尚未开始，敬请期待!");
								return;
							}
						}
					}

					if (connectionStatus != 3) {
						mui.toast("你现在是非WIFI状态下，播放视频会耗费大量流量");
					}

					if (type == 'video') {
						mui.ajax({
							url: api_host + '/api/course/course/getCourseVideo',
							dataType: 'json',
							data: {
								'taskId': taskId
							},
							type: 'get',
							headers: {
								'User-Token': plus.storage.getItem('UserToken')
							},
							timeout: 3000,
							success: function(msg) {
								if (msg.code == 1) {
									class_details.filename = msg.data.filename;
									class_details.PlayURL = msg.data.playInfo.PlayURL;
									class_details.CoverURL = msg.data.videoMeta.CoverURL;
									class_details.status = msg.data.status;
									
									
									if (mui.os.ios) {
										if (video != null) {
											video.close();
										}
										video = plus.video.createVideoPlayer('J_prismPlayer', {
											src: class_details.PlayURL,
											top: '0px',
											left: '0px',
											width: '100%',
											height: vHeight,
											position: 'absolute'
										});
										
										
										plus.webview.currentWebview().append(video);
										video.play();
									} else {
										player = new Aliplayer(option);
										player.dispose();
										$('.prism-player').css("height",vHeight);
										var player = new Aliplayer({
											id: 'J_prismPlayer',
											width: '100%',
											height: vHeight,
											preload: true,
											controlBarVisibility: "click",
											useH5Prism: true,
											autoplay: true,
											"replay": true,
											playsinline: true,
											 /*components: [{
											  name: 'RateComponent',
											  type: RateComponent
											}], */
											cover: "",

											//播放方式一：推荐
											prismType: 2,
											vid: '',
											accId: '',
											accSecret: '',
											apiKey: '',
											// vid : '',
											// playauth : '',
											showBarTime: 5000,
											cover: class_details.CoverURL,
											source: class_details.PlayURL, //视频地址
											skinLayout: [{
													name: "bigPlayButton",
													align: "blabs",
													x: 30,
													y: 80
												},
												{
													name: "H5Loading",
													align: "cc"
												},
												{
													name: "controlBar",
													align: "blabs",
													x: 0,
													y: 0,
													children: [{
															"name": "progress",
															"align": "tlabs",
															"x": 0,
															"y": 0
														}, //隐藏进度条
														{
															"name": "playButton",
															"align": "tl",
															"x": 15,
															"y": 13
														},
														{
															"name": "timeDisplay",
															"align": "tl",
															"x": 10,
															"y": 6
														},
														{
															"name": "fullScreenButton",
															"align": "tr",
															"x": 20,
															"y": 12.5
														},
														{
															"name": "volume",
															"align": "tr",
															"x": 20,
															"y": 12.5
														},
														{
															"name": "speedButton",
															"align": "tr",
															"x": 10,
															"y": 10
														},
														 {
															"name": "setting",
															"align": "tr",
															"x": 15,
															"y": 12
														}, 
													]
												}
											]
										}, function(player) {
											$('#J_prismPlayer video').attr("poster", class_details.CoverURL);
										});
										//阿里云播放器全屏
										var handleReady = function(){
										    plus.screen.lockOrientation("landscape-primary");
										 }
										 player.on('requestFullScreen',handleReady);
										 
										 //阿里云播放器取消全屏
										 var handleReady = function(){
										    plus.screen.lockOrientation("portrait-primary");
										 }
										 player.on('cancelFullScreen',handleReady);
										 
									}
								}
							},
							error: function() {
								console.log('获取视频内容出错了');
							}
						})
					} else if (type == 'live') {
						mui.ajax({
							url: api_host + '/api/course/course/getLive',
							dataType: 'json',
							data: {
								'taskId': taskId
							},
							headers:{'User-Token':plus.storage.getItem('UserToken')},
							type: 'get',
							timeout: 5000,
							success: function(msg) {
								if (msg.code == 1) {
									class_details.PlayURL = msg.data.url;
									if( (end_time > nowTime)  && (nowTime > begin_time)) {
										if (video != null) {
											video.close();
										}
										if(msg.data.live_type == 'live_one'){
											
											player = new Aliplayer(option);
											player.dispose();
											$('.prism-player').css("height",'0');
											mui.openWindow({
												url:class_details.PlayURL,
												createNew: true
											});
										}else{
											video = plus.video.createVideoPlayer('J_prismPlayer', {
												src: class_details.PlayURL,
												top: '0px',
												left: '0px',
												width: '100%',
												height: vHeight,
												position: 'absolute',
												"enable-progress-gesture": "true",
											});
											/*video.setOptions({
												"show-progress": "false"
											})*/
											plus.webview.currentWebview().append(video);
											video.play();
										}
										
									}else if(end_time < nowTime){
										
										if(msg.data.live_type == 'replay_one') {
											
											player = new Aliplayer(option);
											player.dispose();
											$('.prism-player').css("height",'0');
											mui.openWindow({
												url: 'gensee.html',
												createNew: true,
												extras:{
													PlayUrl:class_details.PlayURL
												}
											}) 

										}else if(msg.data.live_type == 'replay'){
											if (video != null) {
											video.close();
											}
											if (mui.os.ios) {
												if (video != null) {
													video.close();
												}
												video = plus.video.createVideoPlayer('J_prismPlayer', {
													src: class_details.PlayURL,
													top: '0px',
													left: '0px',
													width: '100%',
													height: vHeight,
													position: 'absolute'
												});
												plus.webview.currentWebview().append(video);
												video.play();
											}
											else{	
												player = new Aliplayer(option);
												player.dispose();
												$('.prism-player').css("height",vHeight);
												var player = new Aliplayer({
													id: 'J_prismPlayer',
													width: '100%',
													height: vHeight,
													preload: false,
													controlBarVisibility: "click",
													useH5Prism: true,
													"autoplay": true,
													"isLive": false,
													"rePlay": true,
													"playInline": true,
													"preload": true,
													 /*components: [{
													  name: 'RateComponent',
													  type: RateComponent
													}],*/ 
													cover: "",
												
													//播放方式一：推荐
													prismType: 2,
													vid: '',
													accId: '',
													accSecret: '',
													apiKey: '',
													// vid : '',
													// playauth : '',
													showBarTime: 5000,
													cover: picture,
													source: class_details.PlayURL, //视频地址
													skinLayout: [{
															name: "bigPlayButton",
															align: "blabs",
															x: 30,
															y: 80
														},
														{
															name: "H5Loading",
															align: "cc"
														},
														{
															name: "controlBar",
															align: "blabs",
															x: 0,
															y: 0,
															children: [{
																	"name": "progress",
																	"align": "tlabs",
																	"x": 0,
																	"y": 0
																}, //隐藏进度条
																{
																	"name": "playButton",
																	"align": "tl",
																	"x": 15,
																	"y": 13
																},
																{
																	"name": "timeDisplay",
																	"align": "tl",
																	"x": 10,
																	"y": 6
																},
																{
																	"name": "fullScreenButton",
																	"align": "tr",
																	"x": 20,
																	"y": 12.5
																},
																{
																	"name": "speedButton",
																	"align": "tr",
																	"x": 10,
																	"y": 10
																},
																 {
																	"name": "setting",
																	"align": "tr",
																	"x": 15,
																	"y": 12
																}, 
															]
														}
													]
												}, function(player) {
													$('#J_prismPlayer video').attr("poster", picture);
												});
												//阿里云播放器全屏
												var handleReady = function(){
												    plus.screen.lockOrientation("landscape-primary");
												 }
												 player.on('requestFullScreen',handleReady);
												 
												 //阿里云播放器取消全屏
												 var handleReady = function(){
												    plus.screen.lockOrientation("portrait-primary");
												 }
												 player.on('cancelFullScreen',handleReady);
											}
										}
									}
								}
							},
							error: function() {
								console.log('获取视频内容出错了');
							}
						})
					}else{
						
					}
				} else {
					mui.toast('请您先购买课程！');
					return;
				}
				}else {
					mui.toast('您还没有登录，请先登录账号再进行操作哦！');
				}
			}
		},
		computed: {
			dinfindStyle1: function() {
				if (this.tabIndex == 1) {
					return {
						'display': 'block'
					};
				} else {
					return {
						'display': 'none'
					};
				}
			},
			dinfindStyle2: function() {
				if (this.tabIndex == 2) {
					return {
						'display': 'block'
					};
				} else {
					return {
						'display': 'none'
					};
				}
			},
			dinfindStyle3: function() {
				if (this.tabIndex == 3) {
					return {
						'display': 'block'
					};
				} else {
					return {
						'display': 'none'
					};
				}
			}
		},
	})
})

//操作收藏
function add_collection(courseid, name) {
	var api_host = plus.storage.getItem('HOST_URL');
	mui.ajax({
		url: api_host + '/api/other/other/add_collection',
		data: {
			'product_id': courseid,
			'product_title': name.title,
			'collection_info': name,
			'product_type': 'course'
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		headers: {
			'User-Token': plus.storage.getItem('UserToken')
		},
		timeout: 3000,

		success: function(msg) {
			class_details.collection_status = msg.data.collection_status;
			mui.toast(msg.msg, {
				duration: '1000'
			});
		},
		error: function(xhr, type, errorThrown) {
			mui.toast('系统错误，请联系客服！');
		}
	});
}

/**
 * 分享按钮点击事件
 */
function shareHref() {
	plus.share.getServices(successCB, errorCB);
	var title = class_details.details.title;
	var content = class_details.details.title;
	var id = class_details.details.id;
	var href = 'http://edu.gongxuanwang.com/course/' + id;
	var message = '';
	if (mui.os.ios) {
		message = {
			type: "web",
			title: title, //应用名字
			content: content,
			href: href, //分享出去后，点击跳转地址
			thumbs: [class_details.details.smallPicture]
		}
	} else {
		message = {
			title: title, //应用名字
			content: content,
			href: href, //分享出去后，点击跳转地址
			thumbs: [class_details.details.smallPicture]
		}
	}

	//调起分享
	plusShare(message, function(res) {
		//分享回调函数
		if (res) {
			plus.nativeUI.toast("分享成功");
		} else {
			plus.nativeUI.toast("分享失败");
		}
	})
}

function successCB(e) {
	console.log(JSON.stringify(e));
}

function errorCB(e) {
	console.log(JSON.stringify(e));
}

var video = null;

function plusReady() {
	video = new plus.video.VideoPlayer('video', {
		src: class_details.PlayURL,
		autoplay: true
	});
}
document.addEventListener('plus', plusReady, false);

function dataList() {
	class_details.getclass_details();
}

window.addEventListener('dataList', function(event) {
	var embed = plus.webview.currentWebview();
	embed.reload(true);
})

// function pullDown_refresh() {
// 	class_details.getclass_details();
// 	setTimeout(function() {
// 		mui("#refreshContainer").pullRefresh().endPulldownToRefresh(false);
// 	}, 1000);
// }


